//
//  MQNetWorkTools.swift
//  MQWeibo
//
//  Created by 毛强 on 15/12/30.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import AFNetworking

enum MQRequestMethod: String{
    case GET = "GET"
    case POST = "POST"
}

class MQNetWorkTools: AFHTTPSessionManager {
    static let sharedTools:MQNetWorkTools = {
        let instance = MQNetWorkTools()
        instance.responseSerializer.acceptableContentTypes?.insert("text/html")
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    
    typealias MQRequestCallBack = (response:AnyObject?, error: NSError?) -> ()
    
    
    /// 请求数据
    ///
    /// - parameter urlString:  请求地址
    /// - parameter parameters: 请求参数
    /// - parameter finished:   请求成功或者失败的回调
    func request(method: MQRequestMethod = .GET, urlString: String, parameters: AnyObject?, finished:MQRequestCallBack){
        
        // dataTaskWithHttp 是写在 .m 文件里面的
        // 对应在 Swift 中的，就是 private 修饰的方法
        
        // 定义请求成功的闭包
        let success = { (dataTask: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
            finished(response: responseObject, error: nil)
        }
        
        // 定义请求失败的闭包
        let failure = { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
            finished(response: nil, error: error)
        }
        
        if method == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
